<template>
  <div>
    <el-card class="box-card">
      <el-row :gutter="20" class="my-3">
        <el-col :span="4">
          <button
            @click="delAllSelection"
            type="button"
            class="el-button handle-del  el-button--primary  "
          >
            <i class="el-icon-delete"></i><span>批量删除</span>
          </button>
        </el-col>
        <el-col :span="8"
          ><div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              v-model="searchContent"
              clearable
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="search"
              ></el-button>
            </el-input></div
        ></el-col>
        <el-col :span="4"
          ><div class="grid-content bg-purple">
            <el-button type="primary" @click="centerDialogVisible = true">
              <i class="el-icon-plus"></i> <span>添加信息</span>
            </el-button>
          </div></el-col
        >
      </el-row>

      <!-- 用户列表区 -->
      <el-table
        border
        stripe
        :data="cardInfoList"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
      >
        <el-table-column
          type="selection"
          show-overflow-tooltip
        ></el-table-column>

        <el-table-column
          type="index"
          :index="indexSort"
          sortable
          align="center"
          label="#"
          width="50"
        >
        </el-table-column>
        <el-table-column align="center" prop="name" label="名称">
        </el-table-column>
        <el-table-column align="center" label="头像(查看大图)">
          <template #default="scope">
            <el-image
              class="table-td-headPortrait"
              :src="scope.row.img"
              :preview-src-list="[scope.row.img]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="time" label="信息更新时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.time) }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          show-overflow-tooltip
          prop="desc"
          label="简介"
        >
        </el-table-column>
        <el-table-column
          align="center"
          show-overflow-tooltip
          prop="saying"
          label="名言"
        >
        </el-table-column>
        <el-table-column
          align="center"
          show-overflow-tooltip
          prop="mainStory"
          label="主要事迹"
        >
          <template slot-scope="scope">
            <div>
              <p v-html="scope.row.mainStory"></p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="150px" label="操作">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="修改当前信息"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showMessage(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除当前信息"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteid(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- 留言分页pc -->
      <div class="row ">
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            background
            :page-sizes="[4, 6, 8]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户信息"
      :visible.sync="centerDialogVisible"
      width="50%"
      center
      @close="addDialogClose"
    >
      <!-- 表单内容区域 -->
      <el-form
        :model="addForm"
        status-icon
        :rules="addFromRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="name">
          <el-input type="text" clearable v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="名言" prop="saying">
          <el-input type="text" clearable v-model="addForm.saying"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="desc">
          <el-input type="textarea" clearable v-model="addForm.desc"></el-input>
        </el-form-item>
        <el-form-item label="主要事迹" prop="mainStory">
          <el-input
            type="textarea"
            clearable
            v-model="addForm.mainStory"
          ></el-input>
        </el-form-item>

        <el-form-item label="照片" prop="img">
          <el-input
            type="text"
            clearable
            placeholder="请输入更改头像URL地址(http/https)"
            v-model="addForm.img"
          ></el-input>
          <img
            :src="addForm.img"
            alt=""
            class="mt-2"
            style="max-height:150px;"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
        <el-button @click="addresetForm">重置</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="centerDialogVisible2"
      width="50%"
      center
    >
      <!-- @close="editDialogClose" 有未知bug -->
      <!-- 表单内容区域 -->
      <el-form
        :model="editForm"
        status-icon
        :rules="addFromRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="name">
          <el-input type="text" clearable v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="名言" prop="saying">
          <el-input type="text" clearable v-model="editForm.saying"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="desc">
          <el-input
            type="textarea"
            clearable
            v-model="editForm.desc"
          ></el-input>
        </el-form-item>
        <el-form-item label="主要事迹" prop="mainStory">
          <el-input
            type="textarea"
            clearable
            v-model="editForm.mainStory"
          ></el-input>
        </el-form-item>

        <el-form-item label="照片" prop="img">
          <el-input
            type="text"
            clearable
            placeholder="请输入更改头像URL地址(http/https)"
            v-model="editForm.img"
          ></el-input>
          <img
            :src="editForm.img"
            alt=""
            class="mt-3"
            style="max-height:150px;"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
        <!-- <el-button @click="editResetForm">重置</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>
<script>
import qs from "qs";
import formatDateTimes from "@/assets/Tools/date2.js";
export default {
  data() {
    var validImgSrc = (rule, value, callback) => {
      var patt1 = /(http|https):\/\/([\w.]+\/?)\S*/;
      if (!value.match(patt1)) {
        callback(new Error("请按格式填写"));
      } else {
        callback();
      }
    };
    return {
      // 分页
      total: 0,
      pageSize: 6,
      currentPage: 1,
      searchContent: "", // 搜索内容
      cardInfoList: [],
      // 弹出框
      centerDialogVisible: false,
      centerDialogVisible2: false,
      dialogVisible: false,
      //添加
      addForm: {
        name: "",
        time: "",
        saying: "",
        desc: "",
        img: "",
        mainStory: "",
      },
      //修改
      editForm: {
        id: 21,
        name: "",
        time: "",
        saying: "",
        desc: "",
        img: "",
        mainStory: "",
      },
      //验证规则
      addFromRules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        desc: [
          {
            required: true,
            message: "请填写",
            trigger: "blur",
          },
        ],
        saying: [
          {
            required: true,

            message: "请填写",
            trigger: "blur",
          },
        ],
        mainStory: [
          {
            required: true,

            message: "请填写",
            trigger: "blur",
          },
        ],
        img: [
          { required: true, message: "请填写", trigger: "blur" },
          { validator: validImgSrc, trigger: "blur" },
        ],
      },
      //删除列表

      multipleSelection: [], //批量删除列表
    };
  },
  created() {
    this.getCardInfoList();
  },
  methods: {
    formatDate(val) {
      return formatDateTimes.formatDateTime(val);
    },
    // 获取所有用户
    async getCardInfoList() {
      const data = await this.$http.post(
        "/admin/queryCard?" +
          qs.stringify({
            pageNum: this.currentPage,
            pageSize: this.pageSize,
          })
      );
      if (data.code == 200) {
        this.cardInfoList = data.data.records;
        this.total = data.data.total;
      }
      console.log(this.cardInfoList);
    },
    // 分页
    handleSizeChange(pageSize) {
      this.currentPage = 1;
      this.pageSize = pageSize;
      this.getCardInfoList();
    },
    // 跳转页数
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getCardInfoList();
    },
    // 添加用户信息
    async add() {
      this.$refs.addFormRef.validate(async (valid, obj) => {
        if (valid) {
          const data = await this.$http.post("/admin/addCard", {
            name: this.addForm.name,
            desc: this.addForm.desc,
            img: this.addForm.img,
            mainStory: this.addForm.mainStory,
            saying: this.addForm.saying,
          });
          if (data.code == 200) {
            this.addresetForm();
            this.$message.success("添加成功！");
            this.getCardInfoList();
          } else if (data.code == 400) {
            this.$message.error(data.message);
          } else {
            this.$message.error("添加失败!");
          }
        } else {
          this.$message.error("表单填写有误，请检查后提交！");
        }
        this.centerDialogVisible = false;
      });
    },
    // 查询用户信息
    async search() {
      const data = await this.$http.post(
        "/admin/queryCardByName?" +
          qs.stringify({
            name: this.searchContent,
            pageNum: this.currentPage,
            pageSize: this.pageSize,
          })
      );
      if (data.code == 200) {
        this.cardInfoList = data.data.records;
        this.total = data.data.total;
        this.searchContent = "";
      } else {
        this.$message.error("查询用户不存在");
      }
    },
    // 修改用户信息前获取点击用户的信息
    showMessage(row) {
      this.editForm.id = row.id;
      this.editForm.name = row.name;
      this.editForm.saying = row.saying;
      this.editForm.desc = row.desc;
      this.editForm.mainStory = row.mainStory;
      this.editForm.img = row.img;
      this.centerDialogVisible2 = true;
    },
    // 修改用户信息
    async edit() {
      this.$refs.editFormRef.validate(async (valid, obj) => {
        if (valid) {
          const data = await this.$http.post("/admin/updateCard", {
            id: this.editForm.id,
            name: this.editForm.name,
            saying: this.editForm.saying,
            desc: this.editForm.desc,
            mainStory: this.editForm.mainStory,
            img: this.editForm.img,
          });
          if (data.code == 200) {
            this.$message.success("修改成功！");

            this.getCardInfoList();
          } else if (data.code == 400) {
            this.$message.error(data.message);
          } else {
            this.$message.error("修改失败！");
          }
        } else {
          this.$message.error("表单填写有误，请检查后提交！");
        }
        this.centerDialogVisible2 = false;
      });
    },

    //添加 关闭添加界面 清空所填信息
    addresetForm() {
      this.$refs.addFormRef.resetFields();
    }, //添加 取添加改信息 清空所填信息
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 删出用户信息
    async deleteid(row) {
      const confirmresult = await this.$confirm(
        "此操作将永久删除该该用户,不可恢复， 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmresult != "confirm") {
        return this.$message.info("已取消删除！！");
      } else {
        const data = await this.$http.post("/admin/delCard" + row.id);
        if (data.code == 200) {
          this.$message.success("成功删除了 " + row.name + "的信息");
          this.getCardInfoList();
        } else if (data.code == 400) {
          this.$message.error(data.message);
        } else {
          this.$message.error("删除失败");
        }
        this.centerDialogVisible2 = false;
      }
    },
    // 监听哪些行数改变
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量删除按钮
    async delAllSelection() {
      const length = this.multipleSelection.length;
      let delList = [];
      for (let i = 0; i < length; i++) {
        delList.push(this.multipleSelection[i].id);
      }
      const data = await this.$http.post("/admin/delAllCard", {
        list: delList,
      });
      if (data.code == 200) {
        let str = "";
        for (let i = 0; i < length; i++) {
          str += this.multipleSelection[i].name + "、";
        }
        this.$message.error(`成功删除了${str}` + "的信息");
        this.getCardInfoList();
      } else if (data.code == 400) {
        this.$message.error(data.message);
      } else {
        this.$message.error("删除失败");
      }
      this.multipleSelection = []; // 删除后清空列表
    },
    // 排序
    indexSort(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
  },
};
</script>

<style lang="less" scoped>
.table-td-headPortrait {
  width: 40px;
  height: 40px;
}
</style>
